package top.dancun.easstudent.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.dancun.common.entity.RoleEntity;
import top.dancun.common.entity.UserEntity;
import top.dancun.common.utils.PageUtils;
import top.dancun.common.utils.Query;
import top.dancun.common.utils.R;
import top.dancun.easstudent.dao.StudentDao;
import top.dancun.easstudent.entity.ClassEntity;
import top.dancun.easstudent.entity.DormitoryArrangementEntity;
import top.dancun.easstudent.entity.StudentEntity;
import top.dancun.easstudent.entity.UserRoleEntity;
import top.dancun.easstudent.feign.BaseInfoFeign;
import top.dancun.easstudent.feign.service.SysFeignService;
import top.dancun.easstudent.service.DormitoryArrangementService;
import top.dancun.easstudent.service.StudentService;

import java.io.Serializable;
import java.util.*;


@Service("studentService")
public class StudentServiceImpl extends ServiceImpl<StudentDao, StudentEntity> implements StudentService {
    @Autowired
    private BaseInfoFeign baseInfoFeign;

    @Autowired
    private SysFeignService sysFeignService;

    @Autowired
    private DormitoryArrangementService dormitoryArrangementService;

    @Override
    @SuppressWarnings("unchecked")
    public PageUtils queryPage(Map<String, Object> pageParams ,Map<String,String> dataParams) {
        LambdaQueryWrapper<StudentEntity> wrapper = Wrappers.lambdaQuery();
        IPage<StudentEntity> page = new Query<StudentEntity>().getPage(pageParams);
        wrapper.eq(Objects.nonNull(dataParams.get("sid")),StudentEntity::getSid,dataParams.get("sid"))
                .eq(Objects.nonNull(dataParams.get("name")),StudentEntity::getName,dataParams.get("name"));


        R r;
        //查询符合条件的所有班级
        r = baseInfoFeign.getClassList(pageParams);
        //返回值判定
        if("20000".equals(String.valueOf(r.get("code")))){
            if(r.get("data")  instanceof List){
                List<Integer> classId = new ArrayList<Integer>();
                List<HashMap> classList= (List<HashMap>) r.get("data");
                classList.forEach(map->{
                    //获取所有符合条件的班级id
                    ClassEntity classEntity = JSONObject.parseObject(JSON.toJSONString(map),ClassEntity.class);
                    classId.add(classEntity.getClassId());

                });
                if (classId.size()!=0){
                    wrapper.in(StudentEntity::getCid,classId);
                }
            }
            //符合查询条件的学生
            page= this.baseMapper.selectPage(page,wrapper);
            List<Integer> classIds = new ArrayList<>();
//            获取查询出来的学生的所有班级
            page.getRecords().forEach(studentEntity -> {
                classIds.add(Integer.parseInt(studentEntity.getCid()));
            });
            //所有学生的班级id
            r=baseInfoFeign.getClassByIds(classIds);
            if("20000".equals(String.valueOf(r.get("code")))){
                //是否为list
                if(r.get("data")  instanceof List){
                    List<HashMap> classList=  (List<HashMap>)r.get("data");
//                    查询数据后迭代
                    page.getRecords().forEach(studentEntity -> {
                        //远程访问拿到数据后迭代
                       classList.forEach(map -> {
//                           给学生信息添加专业和班级
                           ClassEntity classEntity = JSONObject.parseObject(JSON.toJSONString(map),ClassEntity.class);
                           if(classEntity.getClassId().equals(Integer.parseInt(studentEntity.getCid()))){
                               studentEntity.setClassInfo(classEntity);
                           }
                       });
                    });
                }
            }


        }

        //TODO 自定义sql语句


        return new PageUtils(page);
    }

    @Override
    public PageUtils getByIds(Map<String,Object> params ,List<String> ids,List<Integer> cids) {
        IPage page = new Query().getPage(params);
        page = lambdaQuery()
                .in(Objects.nonNull(ids) && ids.size()!=0, StudentEntity::getSid,ids)
                .or()
                .in(Objects.nonNull(cids) && cids.size()!=0,StudentEntity::getCid,cids).page(page);
        return new PageUtils(page);
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> showAllInfo(String id) {
        Map<String,Object> studentmap = JSON.parseObject(JSON.toJSONString(getById(id)),HashMap.class);
        DormitoryArrangementEntity dormitoryArrangement = dormitoryArrangementService.lambdaQuery().eq(DormitoryArrangementEntity::getStudentId,id).one();
        if(Objects.nonNull(dormitoryArrangement)){
            studentmap.put("bedId",dormitoryArrangement.getBedId());
            studentmap.put("roomId",dormitoryArrangement.getRoomId());
        }

        return studentmap;
    }

    @Override
    public StudentEntity getById(Serializable id) {

        StudentEntity student = this.baseMapper.selectById(id);
        R r;
        r = baseInfoFeign.Classinfo(student.getCid());
        if("20000".equals(String.valueOf(r.get("code")))){
            if(r.get("class") instanceof Map){
                ClassEntity classEntity = JSONObject.parseObject(JSON.toJSONString(r.get("class")),ClassEntity.class);
                student.setClassInfo(classEntity);
                student.setClassCode(classEntity.getClassCode());
                student.setDept(classEntity.getDept());
                student.setMajor(classEntity.getMajor());
            }
        }
        return student;
    }

    @Override
    public boolean save(StudentEntity student) {
        UserEntity user = new UserEntity();
        user.setUid(student.getSid());
        user.setStatus(1);
        user.setPwd(student.getCertNo().substring(12,18));
        RoleEntity role = new RoleEntity();
        role.setRoleId(2l);
        List<RoleEntity> roleList = new ArrayList<>();
        roleList.add(role);
        user.setRoles(roleList);
        sysFeignService.saveUser(user);
        return super.save(student);
    }
}